<?php
// +----------------------------------------------------------------------
// | KITEGO-Admin「开箱即用」「人人全栈」
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2024 https://www.kitego.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed KITEGO并不是自由软件，未经许可不能去掉KITEGO相关版权
// +----------------------------------------------------------------------
// | Author: KITEGO Team <bd@kitego.cn>
// +----------------------------------------------------------------------

namespace app\adminapi\services\setting;

use app\adminapi\validate\setting\SystemRoleValidate;
use app\dao\setting\SystemRoleDao;
use Exception;
use kitego\enum\ApiCodeEnum;

class SystemRoleService
{
    private SystemRoleDao $dao;

    public function __construct(SystemRoleDao $dao)
    {
        $this->dao = $dao;
    }

    /**
     * 角色列表
     * @param array $param
     */
    public function listSystemRole(array $param = [
        'page' => '',
        'pageSize' => '',
    ])
    {
        try {
            $where[] = ['delete_flag', '=', 0];
            if (!empty($param['keyword'])) {
                $where[] = ['label', 'like', '%' . $param['keyword'] . '%'];
            }
            $roleList = $this->dao->listSystemRole($where, $param['page'], $param['pageSize']);
            return success($roleList);
        } catch (Exception $e) {
            return fail($e->getMessage());
        }
    }

    /**
     * 编辑角色
     * @param array $param
     */
    public function editSystemRole(array $param = [
        'id' => '',
        'alias' => '',
        'label' => '',
        'remark' => '',
        'sort' => '',
        'status' => '',
        'deleteFlag' => '',
        'menuIds' => []
    ])
    {
        try {

            Validate(SystemRoleValidate::class)->scene('editSystemRole')->check($param);

            if ($param['id'] == 1) {
                if ($param['deleteFlag'] == 1) {
                    throw new Exception('超管角色禁止删除');
                }
                if ($param['status'] == 0) {
                    throw new Exception('超管角色禁止关闭');
                }
                if ($param['alias'] != 'super') {
                    throw new Exception('超管角色标识不可修改');
                }
            }

            // 角色数据
            $updateData = [
                'alias' => $param['alias'],
                'label' => $param['label'],
                'remark' => $param['remark'],
                'sort' => $param['sort'],
                'status' => $param['status'],
                'delete_flag' => $param['deleteFlag'],
                'menu_ids' => !empty($param['menuIds']) ? implode(',', $param['menuIds']) : ''
            ];

            if (!empty($param['deleteFlag'])) {
                $updateData['delete_time'] = now();
            }
            if (!empty($param['id'])) {
                // 更新菜单
                $updateData['update_time'] = now();
                $id = $this->dao->update($param['id'], $updateData, 'id')->alias;
            } else {
                // 新建菜单
                $updateData['create_time'] = now();
                $id = $this->dao->save($updateData)->id;
            }

            return success(['id' => $id]);
        } catch (Exception $e) {
            return fail($e->getMessage());
        }
    }

    /**
     * 批量删除角色
     * @param array $param
     */
    public function batchDelSystemRole(array $param = ['ids' => []])
    {
        try {
            Validate(SystemRoleValidate::class)->scene('batchDelSystemRole')->check($param);

            if (in_array(1, $param['ids'])) {
                throw new Exception('超管角色禁止删除');
            }

            $where[] = ['id', 'in', $param['ids']];
            $this->dao->update($where, [
                'delete_flag' => 1,
                'delete_time' => now()
            ]);

            return success();
        } catch (Exception $e) {
            return fail($e->getMessage());
        }
    }

    /**
     * 获取角色菜单
     * @param array $param
     */
    public function getRoleMenuIds(array $param = [
        'roleId' => ''
    ])
    {
        Validate(SystemRoleValidate::class)->scene('getRoleMenuIds')->check($param);

        // 所有菜单id
        $res = app()->make(SystemMenuService::class)->listSystemMenu();
        $res = $res->getData();
        if ($res['status'] != ApiCodeEnum::OK) exception($res['message']);

        $menu = $res['data'];

        // 权限对应菜单ids
        $role = app()->make(SystemRoleDao::class)->listSystemRole([['id', '=', $param['roleId']]]);
        if (empty($role['data'])) {
            throw new Exception('角色不存在');
        }
        $menuIds = empty($role['data'][0]['menu_ids']) ? [] : explode(',', $role['data'][0]['menu_ids']);

        return success([
            'menu' => $menu,
            'checked' => $menuIds,
        ]);
    }
}